package org.dizena.blog.starter.config.demo0;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.dizena.common.constant.ConstantHeaderKey;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Enumeration;
import java.util.Map;
import java.util.UUID;

public class HeaderHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            HeaderInheritableUtil.set(name, request.getHeader(name));
        }
        Map<String, String> header = HeaderInheritableUtil.get();
        if (!header.containsKey(ConstantHeaderKey.ACCESS_ID)) {
            String reqId = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");
            request.setAttribute(ConstantHeaderKey.ACCESS_ID, reqId);
            HeaderInheritableUtil.set(ConstantHeaderKey.ACCESS_ID, reqId);
        }
        if (!header.containsKey(ConstantHeaderKey.ACCESS_TIME)) {
            String reqTime =  String.valueOf(System.currentTimeMillis());
            request.setAttribute(ConstantHeaderKey.ACCESS_TIME, reqTime);
            HeaderInheritableUtil.set(ConstantHeaderKey.ACCESS_TIME, reqTime);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HeaderInheritableUtil.remove();
    }
}